<template lang="pug">
.ignore-registration-form
  //- div.elFormtitle 患者基本信息
  mt-form(v-bind="RegistrationFormProps",ref="formRef")
  //- div.elFormtitle 患者就诊信息  
  //- mt-form(v-bind="visitFormProps")
  PatientEdit(v-model="showPatientEdit")
</template>
<script setup lang="ts">
import { type FormItemProps, type FormProps, Form, Select, Button } from "@scmt/common-components";
import { useApi, type ApiBasedOptions } from "@scmt/core-api";
import type { RegistrationEntity } from "@scmt/api-pacs-registration";
import { useUser } from "@scmt/common-store";
import { useRequest } from "@scmt/common-hooks";
import { type PatientEntity } from "@scmt/api-patient";
import { PatientEdit } from "@scmt/common-api-components";

const showPatientEdit = ref(false);
const user = useUser();
//添加 Props属性
const props = defineProps({
  selectRegistration: Object,
  isRegistration: Boolean,
});
const $api = useApi();
const editingObj = ref<RegistrationEntity>($api.pacs.registration.$$createEntity({}));
const formRef = ref<null | InstanceType<typeof Form>>(null);
//校验
const validate = (
  callback?: (valid: boolean, model: any) => Promise<void> | void
) => {
  //@ts-ignore
  formRef.value?.validate((valid: any) => {
    typeof callback === "function" && callback(valid, editingObj.value);
  });
};
//清除校验提示
const clearValidation = () => {
  //@ts-ignore
  formRef.value?.resetFields();
}
defineExpose({ validate, clearValidation });

const patients = ref<ApiBasedOptions<PatientEntity>>([]);
const { request } = useRequest({
  patients: async (keyword: string) => {
    if (!keyword && patients.value.length) {
      return patients.value;
    }
    return $api.patient.listAsOptions({ keyword });
  },


});
const queryPatients = (keyword: string) => {
  return request("patients", keyword);
};
//是否允许修改
const isDisabled = computed<boolean>(() => {
  return Boolean(props.isRegistration || "" != editingObj.value.id)
});

const RegistrationFormProps = computed<FormProps>(() => {
  const formItems: FormItemProps[] = [
    {
      prop: "inspectionNumber",
      label: "检查编号",
      required: false,
      disabled: true,
      placeholder: "检查编号系统自动生成"
    },
    {
      prop: "name",
      label: "患者姓名",
      required: true,
      disabled: isDisabled.value,
      render: () => {
        return h(
          "div",
          {
            style: {
              display: "flex",
              alignItems: "center",
              width: "100%",
            },
          },
          [
            h(Select, {
              modelValue: editingObj.value?.name,
              style: {
                flex: 1,
              },
              onSelect: (val: string) => {
                //@ts-ignore
                Object.assign(editingObj.value, {
                  //@ts-ignore
                  patientId: val.value,
                  //@ts-ignore
                  name: val.label,
                  //@ts-ignore
                  patientNumber: val._raw.patientFileNumber,
                  //@ts-ignore
                  sex: val._raw.sex,
                  //@ts-ignore
                  age: val._raw.age,
                  //@ts-ignore
                  address: val._raw.detailedContactAddress,
                  //@ts-ignore
                  idCard: val._raw.idCard,
                });
              },
              remoteMethod: queryPatients,
              render: "patient-table",
              placeholder: "请选择患者",
              disabled: isDisabled.value,
            }),
            h(Button, {
              label: "快速建档",
              type: "primary",
              disabled: isDisabled.value,
              style: {
                flexShrink: 0,
                marginLeft: "var(--mt-margin)",
              },
              onClick: () => {
                showPatientEdit.value = true;
              },
            }),
          ]
        );
      },
    },
    {
      prop: "idCard",
      label: "身份证号",
      required: true,
      span: 12,
      disabled: isDisabled.value,
      rules: [{
        type: "string",
        required: true,
        message: "请输入身份号",
        trigger: "change",
      },
      { validator: validID, trigger: "blur" }],
    },
    {
      prop: "sex",
      label: "性别",
      required: true,
      as: "select",
      disabled: isDisabled.value,
      options: {
        loadMethod: () => {
          return [
            { label: "男", value: "男" },
            { label: "女", value: "女" },
          ];
        },
      },
    },
    {
      prop: "age",
      label: "年龄",
      required: false,
      span: 12,
      disabled: isDisabled.value,
      options: {
        appendText: "岁"
      }
    },
    {
      prop: "address",
      label: "联系地址",
      required: false,
      disabled: isDisabled.value,
      span: 12,
    },
    {
      prop: "patientType",
      label: "业务来源",
      required: true,
      disabled: isDisabled.value,
      as: "select",
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("patient-type"),
      },
    },
    // {
    //   prop: "admissionNumber",
    //   label: "住院号",
    //   required: false,
    //   disabled: isDisabled.value,
    // },
    {
      prop: "outpatientNumber",
      label: "检查编号",
      required: false,
      disabled: isDisabled.value,
    },
    // {
    //   prop: "ward",
    //   label: "病区",
    //   required: false,
    //   as: "select",
    //   disabled: isDisabled.value,
    // },
    // {
    //   prop: "bedNumber",
    //   label: "床位号",
    //   required: false,
    //   as: "select",
    //   disabled: isDisabled.value,
    // },
    {
      prop: "applyOfficeId",
      label: "申请科室",
      labelKey: "applyOfficeName",
      required: false,
      as: "select",
      disabled: isDisabled.value,
      options: {
        render: "office-table",
        loadMethod: () => $api.upms.org.listAsOptions(),
      },
    },
    {
      prop: "applyDoctorId",
      label: "申请医生",
      labelKey: "applyDoctorName",
      required: false,
      disabled: isDisabled.value,
      as: "select",
      options: {
        render: "doctor-table",
        //@ts-ignore
        loadMethod: () => $api.user.listDoctorAsOptions({ officeId: editingObj.value?.applyingOfficeId }),
      }
    },
    {
      prop: "urgent",
      label: "是否加急",
      required: false,
      disabled: isDisabled.value,
      as: "switch",
      options: {
        activeValue: 1,
        inactiveValue: 0
      }
    },
    {
      prop: "clinicalDiagnosis",
      label: "检查技师",
      required: false,
      as: "select",
      disabled: isDisabled.value,
      options: {
        render: "doctor-table",
        //@ts-ignore
        loadMethod: () => $api.user.listDoctorAsOptions({ officeId: editingObj.value?.applyingOfficeId }),
      }
    },

  ];

  const editProps: FormProps = {
    model: editingObj.value,
    items: formItems,
    columns: 2,
  };

  return editProps;
});
const isIdCard = ref(false);
// 身份证验证
const validID = (rule: any, value: any, callback: any) => {
  isIdCard.value = false;
  // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
  let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  if (rule && reg.test(value)) {
    isIdCard.value = true;
    go(value.length);
    callback();
  } else {
    callback(new Error("身份证号码不正确"));
  }
};

// 实现自动生成生日，性别，年龄
const go = (val: any) => {
  let iden = "" + props.selectRegistration?.idCard;
  let sex = "";
  let birth = null;
  let myDate = new Date();
  let month = myDate.getMonth() + 1;
  let day = myDate.getDate();
  let age = 0;
  if (val === 18) {
    age = myDate.getFullYear() - Number(iden.substring(6, 10)) - 1;
    sex = iden.substring(16, 17);
    birth =
      iden.substring(6, 10) +
      "-" +
      iden.substring(10, 12) +
      "-" +
      iden.substring(12, 14);
    if (
      Number(iden.substring(10, 12)) < month ||
      (Number(iden.substring(10, 12)) == month &&
        Number(iden.substring(12, 14)) <= day)
    )
      age++;
  }
  if (val === 15) {
    age = myDate.getFullYear() - Number(iden.substring(6, 8)) - 1901;
    sex = iden.substring(13, 14);
    birth =
      "19" +
      iden.substring(6, 8) +
      "-" +
      iden.substring(8, 10) +
      "-" +
      iden.substring(10, 12);
    if (
      Number(iden.substring(8, 10)) < month ||
      (Number(iden.substring(8, 10)) == month &&
        Number(iden.substring(10, 12)) <= day)
    )
      age++;
  }
  if (Number(sex) % 2 === 0) sex = "女";
  else sex = "男";
  //@ts-ignore
  Object.assign(props.selectRegistration, { "sex": sex, "age": age + "", "birth": birth + "" });

  // props.selectRegistration?.sex = sex;
  // props.selectRegistration?.age = age + "";
};

watch(
  () => props.selectRegistration,
  (item) => {
    editingObj.value = $api.pacs.registration.$$createEntity({});
    if (item && item.id) {
      item.patientType = item.patientType + "";
      item.clinicalDiagnosis = user.info?.userId;
      editingObj.value = $api.pacs.registration.$$createEntity(item)
    }
  },
  {
    immediate: true,
  }
);

</script>

<style lang="less" scoped>
.ignore-registration-form {
  margin-top: 0px !important;

  .elFormtitle {
    height: 18px;
    font-size: 14px;
    margin-bottom: 5px;
    color: #999;
  }

  :deep(.el-form-item) {
    margin-bottom: 15px;
  }
}
</style>
